<?php
/**
 * AjaxController
 *
 * @author
 * @version
 */
require_once 'BaseAjaxController.php';
require_once 'configs/Config.php';

class AjaxController extends BaseAjaxController {
	
	public function getPurifyWhihelloteList() {
		return array ("password" );
	}
	
	public function indexAction() {
		$this->view->response = array ('result' => 'success' );
	}
	
	/**
	 * Check if the username has already existed in the db
	 */
	public function checkUsernameAction() {
		if ($this->hasInputParam ( 'username' )) {
			$uname = $this->getRequest ()->getParam ( 'username' );
			$error = $this->_helper->checkUsername ( $uname );
			if ($error) {
				$this->view->response = $this->createErrorResult ( $error );
			} else {
				$this->view->response = array ('result' => 'success' );
			}
		} else {
			$this->view->response = array ('result' => 'success', 'warning' => 'no username specified' );
		}
	}
	/**
	 * Check if email is available and well-formed
	 */
	public function checkEmailAction() {
		if ($this->hasInputParam ( 'email' )) {
			$email = $this->getRequest ()->getParam ( 'email' );
			$error = $this->_helper->checkEmailWellForm ( $email );
			if ($error) {
				$this->view->response = $this->createErrorResult ( $error );
			} else {
				$error = $this->_helper->checkEmail ( $email );
				if ($error) {
					$this->view->response = $this->createErrorResult ( $error );
				} else {
					$this->view->response = array ('result' => 'success' );
				}
			}
		} else {
			$this->view->response = array ('result' => 'success', 'warning' => 'no email specified' );
		}
	}
	/**
	 * Action for logging in the system
	 */
	public function loginAction() {
		$errorMsg = '';
		//check if this is a login submit
		if ($this->hasInputParam ( 'username' ) && $this->hasInputParam ( 'password' )) {
			$uname = $this->getRequest ()->getParam ( "username" );
			$pwd = $this->getRequest ()->getParam ( "password" );
			$block = $this->GetSessionValue ( 'block', 'block' );
			if ($block == 1) {
				$errorMsg = Message::LOGIN_FAIL_EXCEED_LIMIT . '.';
			} else {
				$uid = UserAuth::AuthenticateUser ( $uname, $pwd );
				if ($uid !== true) {
					$loginAttempt = $this->GetSessionValue ( 'userAuth', 'loginAttempt' );
					if (! $loginAttempt) {
						$loginAttempt = 0;
					}
					$loginAttempt ++;
					$errorMsg = 'Tên đăng nhập và mật khẩu không hợp lệ.<br>Bạn đã đăng nhập thất bại ' . $loginAttempt . ' lần.';
					$this->SetSessionValue ( 'userAuth', 'loginAttempt', $loginAttempt );
					if ($loginAttempt >= GlobalConfig::$maxLoginAttempt) {
						$this->SetSessionValue ( 'block', 'block', '1' );
						$this->SetSessionTimeout ( 'block', GlobalConfig::$blockSessionTimeout );
						$this->SetSessionValue ( 'userAuth', 'loginAttempt', null );
					}
				} else {
					$this->sendPersistentLoginCookie ( $uname );
				}
			}
		} else {
			$errorMsg = Message::NEED_UNAME_N_PASSWD;
		}
		if ($errorMsg != '') {
			$this->view->response = $this->createErrorResult ( $errorMsg );
		} else {
			$this->checkUser ();
			$user = $this->getUser ();
			$this->view->response = array ('result' => array ('userid' => $user->id, 'name' => $user->name ) );
		}
	}
	private function sendPersistentLoginCookie($uname) {
		//login successfully
		require_once 'models/User.php';
		if ($this->_hasParam ( 'persistent' )) {
			$persistent = $this->_getParam ( 'persistent' );
			if ($persistent === '1') {
				//create a new PersistentLogin
				require_once 'models/PersistentLogin.php';
				$pl = new PersistentLogin ( $uname );
				$pl->insertRow ();
				$cookies = $pl->createCookies ();
				//send cookies to client
				$this->_helper->sendCookies ( $cookies );
			}
		}
	}
	public function createNewProfileAction() {
		$profile = new Profile ( NULL );
		$user = $this->getUser ();
		if ($user != null) {
			$userid = $user->id;
			$val = $profile->createNewProfileWithTerm ( $this->_getParam ( 'name' ), 14, $userid );
			if ($val == null) {
				$this->view->response = array ('result' => 'error' );
			} else {
				$this->view->response = array ('result' => $val );
			}
		} else {
			$this->view->response = $this->createErrorResult ( 'No User' );
		}
	}
	private static function cmp($a, $b) {
		if (strlen ( $a ) == strlen ( $b ))
			return 0;
		if (strlen ( $a ) > strlen ( $b ))
			return 1;
		return - 1;
	}
	public function getProfileDetailAction() {
		// Nếu có id => Lấy profile
		if ($this->hasInputParam ( 'id' )) {
			$userID = $this->_getParam ( 'id' );
		} else {
			$user = $this->getUser ();
			if ($user == null) {
				$this->view->response = $this->createErrorResult ( 'User not logged in' );
				return;
			}
			$userID = $user->id;
		}
		
		$u = User::getUserFromUniqueKey ( 'id', $userID );
		if ($u == null) {
			$this->view->response = $this->createErrorResult ( 'User not exist' );
			return;
		}
		$profileid = $u->primary_bind;
		
		// Nếu không có id, kiểm tra user
		$p = new Profile ( array ('profile_id' => $profileid, 'lang' => 'content_en' ) );
		if (! $p->isExist ()) {
			$this->view->response = $this->createErrorResult ( 'Profile not exist' );
			return;
		}
		$result = array ('profile_id' => $profileid, 'data' => $p->getData () );
		$this->view->response = array ('result' => $result );
	}
	
	public function checkUserStatusAction() {
		$user = $this->getUser ();
		if ($user == null) {
			$this->view->response = array ('result' => 0 );
		} else {
			$this->view->response = array ('result' => array ('userid' => $user->id, 'name' => $user->name ) );
		}
	}
	
	public function registerAction() {
		$errors = $this->validateRegisterRequest ();
		if (count ( $errors ) > 0) {
			$this->view->response = $this->createErrorResult ( $errors );
		} else {
			$username = $this->getRequest ()->getParam ( "username" );
			$passwd = $this->getRequest ()->getParam ( "password" );
			$enc_passwd = Utils::EncryptedPassword ( $passwd );
			$email = $this->getRequest ()->getParam ( "email" );
			$registerdate = $this->_helper->getCurrentDate ();
			$additional = $this->_getParam('additional');
//			var_dump($additional);
//			die();
			$bind = null;
			$user = new User ( null );
			$activation = Utils::createActivationCode($username);
			$data = array ('username' => $username, 'password' => $enc_passwd, 'role' => 'user', 'email' => $email, 'block' => 0, 'activated' => 0, 'activation' => $activation, 'activation_date' => $registerdate, 'registerDate' => $registerdate );
			$user->insertRowWithData ( $data );

			$user = new User($username);
			//create profile for user
			require_once('models/Profile.php');
			$p = new Profile ( null );
			$val = $p->createProfile ( $user->getUserID(), $additional);
			
			$this->sendMail($username, $email, $activation);
			$this->view->response = array ('result' => array ('profile_id' => $bind ) );
		}
	}
	
	public function validateRegisterRequest() {
		$generalError = array ();
		if (! $this->hasInputParam ( 'username' )) {
			$generalError [] = array('type'=>'username', 'msg'=>Message::ERROR_NO_USERNAME);
		} else {
			$uname = $this->getRequest ()->getParam ( 'username' );
			$error = $this->_helper->checkUsername ( $uname );
			if ($error) {
				$generalError [] = array('type'=>'username', 'msg'=>$error);
			}
		}
		if (! $this->hasInputParam ( 'password' )) {
			$generalError [] = array('type'=>'password', 'msg'=>Message::ERROR_NO_PASSWD);
		} else {
			$result = $this->_helper->checkPairedValue ( 'password', 'repassword' );
			if (! $result) {
				$generalError [] = array('type'=>'repassword', 'msg'=>Message::ERROR_PASSWD_MISMATCH);
			} else {
				$pwd = $this->_getParam ( 'password' );
				$result = $this->_helper->checkPasswordWellForm ( $pwd );
				if ($result) {
					$generalError [] = array('type'=>'password', 'msg'=>$result);
				}
			}
		}
		if (! $this->hasInputParam ( 'email' )) {
			$generalError [] = array('type'=>'email', 'msg'=>Message::ERROR_NO_EMAIL);
		} else {
			$email = $this->getRequest ()->getParam ( 'email' );
			$error = $this->_helper->checkEmailWellForm ( $email );
			if ($error) {
				$generalError [] = array('type'=>'email', 'msg'=>$error);
			} else {
				$error = $this->_helper->checkEmail ( $email );
				if ($error) {
					$generalError [] = array('type'=>'email', 'msg'=>$error);
				}
			}
		}
		return $generalError;
	}
	
	public function getAnnouncementAction() {
		$this->view->response = array ('result' => "BKProfile vừa gặp một số trục trặc với hệ thống, hiện tại những bạn nào không thể đăng nhập được tài khoản tại BKProfile vui lòng làm theo hướng dẫn ở <a href='#page/RecoverError'>trang này</a>. Xin lỗi các bạn về sự bất tiện này." );
	}
	
	public function logoutAction() {
		$this->logout ();
		$this->view->response = array ('result' => 'success' );
	}
	
	public function renderCaptchaAction() {
		$this->view->response = array ('result' => $this->_helper->createCaptcha () );
	}
	
	public function sendMail($username, $email, $activation){
//		try {
			$success = $this->_helper->sendActivationEmail($username, $email, $activation);
//		} catch (Exception $e) {
//			$this->view->response = $this->createErrorResult('Error cannot sending welcome email');
//		}
	}
	
	public function activationAction(){
		if(!$this->hasInputParam("code")){
			$this->view->response = $this->createErrorResult('Lỗi trong đường dẫn');
			return;
		}
		if(!$this->hasInputParam("username")){
			$this->view->response = $this->createErrorResult('Lỗi trong đường dẫn');
			return;
		}
		$code = $this->_getParam("code");
		$uname = $this->_getParam("username");
		$param = array();
		$param['username'] = $uname;
		$user = new User($param);
		if($user->activated == 1){
			$this->view->response = array('result'=>array('code' => 4));
			return;
		}
		$success = $this->_helper->checkActivationCode($user, $code);
		$this->view->response = array('result'=>array('code' => $success));
	}

	public function getKeywordsAction()	{
		require_once ('models/Keywords.php');
		$keywords = Keywords::getInstance()->getKeywords();
		$this->view->response = array('result'=>$keywords);
	}
}